<?php

class System {
	
	private $_uri;
	private $_explode;
	private $_controller;
	private $_action;
	private $_params;
	
	public function __construct(){
		$this->setUri();
		$this->setExplode();
		$this->setController();
		$this->setAction();
		$this->setParams();
	}
	
	private function setUri() {
		$this->_uri = ( isset($_GET['uri']) ? $_GET['uri'] : "welcome/index" );;
	}
	
	private function setExplode() {
		$this->_explode = explode("/", $this->_uri);
	}
	
	private function setController() {
		$this->_controller = $this->_explode[0];
	}
	
	private function setAction() {
		$action = ( !isset($this->_explode[1]) || $this->_explode[1] == null || $this->_explode[1] == "index" ) ? "index_action" : $this->_explode[1];
		$this->_action = $action;
	}
	
	private function setParams() {
		$this->_params = array();
		if( end($this->_explode) == null )
			array_pop($this->_explode);
		if( count($this->_explode) % 2 == 0 )
			for ($i = 2; $i < count($this->_explode); $i+=2) 
				$this->_params[ $this->_explode[$i] ] = $this->_explode[$i+1];
	}
	
	public function getAction() {
		$action = explode("_", $this->_action);
		return $action[0];
	}
	
	public function getActionMethod() {
		return $this->_action;
	}
	
	public function getController() {
		return $this->_controller;
	}
	
	protected function error404($uriReturn = ""){
		$error = View::create("_error/404")
							->set("base", BASE)
							->set("linkReturn", $uriReturn);
		echo $error->output();
		exit();
	}

	protected function getParam($name=null) {
		if ($name != null) {
			if( array_key_exists($name, $this->_params) )
				return $this->_params[$name];
			else
				return false;
		}
		return $this->getParams();
	}
	
	protected function getParamId($name="id") {
		if ($name != null) {
			if( array_key_exists($name, $this->_params) ){
				if( (($name == "id") || (substr($name, strlen($name)-3) == "_id")) )
					return intval(Encryption::decode($this->_params[$name]));
			}else{
				return false;
			}
		}
		return null;
	}

	protected function getParams() {
		return $this->_params;
	}

	protected function containsParam($param) {
		return is_array($this->_params) ? array_key_exists($param, $this->_params) : null;
	}

	public function run() {
		
		$controller = ucfirst($this->_controller)."Controller";
		$action = $this->_action;

		$controller_path = APP_CONTROLLERS . $controller . ".php";
		
		if( !file_exists($controller_path) )
			$this->error404();
		
		require_once($controller_path);
		
		$app = new $controller();
		
		if( !method_exists($app, $action) )
			$this->error404($this->_controller);
		
		$app->before();
		$app->$action();
		$app->after();
		
	}
	
	
}

?>